﻿using UnityEngine;
using DG.Tweening;
using DG.Tweening.Core;

namespace Miao.UI
{
    public class PopInBounceUIMotion : BaseUIMotion
    {
        private Sequence sequenceHandle;
        private float _duration;
        private float _bounceScale;
        private Vector3 baseLocalScale;

        public PopInBounceUIMotion(float duration = 1f, float bounceScale = 1.2f)
        {
            _duration = duration;
            _bounceScale = bounceScale;
        }

        public override void Init()
        {
            baseLocalScale = TweenGameObject.transform.localScale;
        }

        public override void Play(bool forward, TweenCallback complete)
        {
            if (sequenceHandle != null)
            {
                sequenceHandle.Complete();
                sequenceHandle = null;
            }

            if (forward)
            {
                PlayPopInBounceAnimation(complete);
            }
            else
            {
                PlayPopOutAnimation(complete);
            }
        }

        private void PlayPopInBounceAnimation(TweenCallback complete)
        {
            // 设置初始状态为0缩放
            TweenGameObject.transform.localScale = Vector3.zero;

            // 创建动画序列
            sequenceHandle = DOTween.Sequence();

            // 第一阶段：从0缩放到正常大小（弹性效果）
            sequenceHandle.Append(TweenGameObject.transform.DOScale(baseLocalScale, _duration * 0.7f)
                .SetEase(Ease.OutElastic));

            // 第二阶段：快速涨大到bounce scale
            sequenceHandle.Append(TweenGameObject.transform.DOScale(baseLocalScale * _bounceScale, _duration * 0.15f)
                .SetEase(Ease.OutQuad));

            // 第三阶段：缩回到正常大小
            sequenceHandle.Append(TweenGameObject.transform.DOScale(baseLocalScale, _duration * 0.15f)
                .SetEase(Ease.InQuad));

            // 设置完成回调
            sequenceHandle.OnComplete(complete);
        }

        private void PlayPopOutAnimation(TweenCallback complete)
        {
            // 反向播放时直接缩小到0
            Vector3 fromScale = baseLocalScale;
            Vector3 toScale = Vector3.zero;

            TweenGameObject.transform.localScale = fromScale;
            sequenceHandle = DOTween.Sequence();
            sequenceHandle.Append(TweenGameObject.transform.DOScale(toScale, _duration)
                .SetEase(Ease.InElastic));
            sequenceHandle.OnComplete(complete);
        }
    }
}